<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑数据库连接"
    width="550px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
    class="connection-dialog"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
      class="connection-form"
    >
      <!-- 基本信息 -->
      <el-card shadow="never" class="mb-3 border border-gray-200 rounded-lg">
        <template #header>
          <div class="flex items-center justify-between py-1">
            <span class="text-sm font-medium text-gray-700">基本信息</span>
          </div>
        </template>
        
        <el-form-item label="连接名称" prop="name" class="mb-3">
          <el-input
            v-model="form.name"
            placeholder="请输入连接名称"
            clearable
            class="text-sm"
          />
        </el-form-item>

        <el-form-item label="数据库类型" prop="type" class="mb-0">
          <el-select
            v-model="form.type"
            placeholder="请选择数据库类型"
            @change="handleTypeChange"
            class="w-full text-sm"
            disabled
          >
            <el-option
              v-for="type in supportedTypes"
              :key="type"
              :label="getTypeLabel(type)"
              :value="type"
            >
              <div class="flex items-center">
                <el-icon class="mr-2">
                  <component :is="getTypeIcon(type)" />
                </el-icon>
                {{ getTypeLabel(type) }}
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-card>

      <!-- 连接信息 -->
      <el-card v-if="form.type && form.type !== 'sqlite'" shadow="never" class="mb-3 border border-gray-200 rounded-lg">
        <template #header>
          <div class="flex items-center justify-between py-1">
            <span class="text-sm font-medium text-gray-700">连接信息</span>
          </div>
        </template>

        <el-form-item label="主机地址" prop="host" class="mb-3">
          <el-input
            v-model="form.host"
            placeholder="localhost"
            clearable
            class="text-sm"
          />
        </el-form-item>

        <el-form-item label="端口" prop="port" class="mb-3">
          <el-input-number
            v-model="form.port"
            :min="1"
            :max="65535"
            controls-position="right"
            class="w-full text-sm"
          />
        </el-form-item>

        <el-form-item label="用户名" prop="username" class="mb-3">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            clearable
            class="text-sm"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password" class="mb-0">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
            clearable
            class="text-sm"
          />
        </el-form-item>
      </el-card>

      <!-- SQLite 特有配置 -->
      <el-card v-if="form.type === 'sqlite'" shadow="never" class="mb-3 border border-gray-200 rounded-lg">
        <template #header>
          <div class="flex items-center justify-between py-1">
            <span class="text-sm font-medium text-gray-700">文件信息</span>
          </div>
        </template>
        
        <el-form-item label="文件路径" prop="filePath" class="mb-0">
          <div class="flex gap-2">
            <el-input
              v-model="form.filePath"
              placeholder="请选择SQLite文件路径"
              readonly
              class="text-sm"
            />
            <el-button type="primary" @click="selectSQLiteFile" class="!h-[32px] text-xs">
              <el-icon class="mr-1"><Folder /></el-icon>
              浏览
            </el-button>
          </div>
        </el-form-item>
      </el-card>

      <!-- 高级选项 -->
      <el-card shadow="never" class="border border-gray-200 rounded-lg">
        <template #header>
          <div class="flex items-center justify-between py-1">
            <span class="text-sm font-medium text-gray-700">高级选项</span>
            <el-switch v-model="showAdvanced" class="scale-90" />
          </div>
        </template>

        <div v-if="showAdvanced" class="transition-all">
          <template v-if="form.type === 'mysql'">
            <el-form-item label="字符集" class="mb-3">
              <el-select v-model="form.charset" placeholder="utf8mb4" clearable class="w-full text-sm">
                <el-option label="utf8mb4" value="utf8mb4" />
                <el-option label="utf8" value="utf8" />
                <el-option label="latin1" value="latin1" />
              </el-select>
            </el-form-item>

            <el-form-item label="时区" class="mb-3">
              <el-input
                v-model="form.timezone"
                placeholder="Asia/Shanghai"
                clearable
                class="text-sm"
              />
            </el-form-item>
          </template>

          <template v-if="form.type === 'postgresql'">
            <el-form-item label="SSL模式" class="mb-3">
              <el-select v-model="form.sslMode" placeholder="disable" clearable class="w-full text-sm">
                <el-option label="disable" value="disable" />
                <el-option label="require" value="require" />
                <el-option label="verify-ca" value="verify-ca" />
                <el-option label="verify-full" value="verify-full" />
              </el-select>
            </el-form-item>
          </template>

          <el-form-item label="连接参数" class="mb-3">
            <el-input
              v-model="form.options"
              type="textarea"
              :rows="2"
              placeholder="额外的连接参数，如：timeout=30s&readTimeout=10s"
              class="text-sm"
            />
          </el-form-item>

          <el-form-item class="mb-0">
            <el-checkbox v-model="form.isDefault" class="text-sm">
              设为默认连接
            </el-checkbox>
          </el-form-item>
        </div>
        <div v-else class="text-center py-2 text-xs text-gray-500">
          <span>打开开关查看和编辑高级选项</span>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="flex justify-between items-center">
        <el-button @click="testConnection" :loading="testing" type="info" class="text-xs !h-[32px]">
          <el-icon class="mr-1"><Connection /></el-icon>
          测试连接
        </el-button>
        <div class="flex gap-2">
          <el-button @click="handleClose" class="text-xs !h-[32px]">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting" class="text-xs !h-[32px]">
            保存
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useConnectionStore } from '@/stores'
import { DatabaseTypes, DefaultPorts, validateConnectionConfig } from '@/services/database'

const emit = defineEmits(['update:modelValue', 'success'])
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  connection: {
    type: Object,
    default: null
  }
})

const connectionStore = useConnectionStore()

// 响应式数据
const formRef = ref()
const dialogVisible = ref(false)
const showAdvanced = ref(false)
const testing = ref(false)
const submitting = ref(false)

// 表单数据
const form = ref({
  id: '',
  name: '',
  type: '',
  host: 'localhost',
  port: 3306,
  username: '',
  password: '',
  database: '', // 保留字段但不在UI中显示
  filePath: '',
  charset: 'utf8mb4',
  timezone: '',
  sslMode: 'disable',
  options: '',
  isDefault: false
})

// 计算属性
const supportedTypes = computed(() => {
  return [
    DatabaseTypes.MYSQL,
    DatabaseTypes.POSTGRESQL,
    DatabaseTypes.SQLITE,
    DatabaseTypes.SQLSERVER,
    DatabaseTypes.DAMENG
  ]
})

// 表单验证规则
const rules = computed(() => {
  const baseRules = {
    name: [
      { required: true, message: '请输入连接名称', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择数据库类型', trigger: 'change' }
    ]
  }

  if (form.value.type === DatabaseTypes.SQLITE) {
    baseRules.filePath = [
      { required: true, message: '请选择SQLite文件路径', trigger: 'blur' }
    ]
  } else if (form.value.type) {
    baseRules.host = [
      { required: true, message: '请输入主机地址', trigger: 'blur' }
    ]
    baseRules.port = [
      { required: true, message: '请输入端口号', trigger: 'blur' },
      { type: 'number', min: 1, max: 65535, message: '端口号必须在1-65535之间', trigger: 'blur' }
    ]
    baseRules.username = [
      { required: true, message: '请输入用户名', trigger: 'blur' }
    ]
  }

  return baseRules
})

// 监听对话框显示状态
watch(() => props.modelValue, async (val) => {
  dialogVisible.value = val
  if (val && props.connection) {
    await loadConnectionData()
  }
})

watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 监听连接数据变化
watch(() => props.connection, async (connection) => {
  if (connection && dialogVisible.value) {
    await loadConnectionData()
  }
})

// 方法
const loadConnectionData = async () => {
  if (!props.connection) return
  
  try {
    // 从后端获取配置数据
    console.log('Loading connection data for:', props.connection.id)
    const config = await connectionStore.getConfig(props.connection.id)
    console.log('Loaded config:', {
      id: config.id,
      name: config.name,
      hasPassword: !!config.password,
      passwordLength: config.password ? config.password.length : 0
    })
    
    form.value = {
      id: config.id,
      name: config.name || '',
      type: config.type || '',
      host: config.host || 'localhost',
      port: config.port || DefaultPorts[config.type] || 3306,
      username: config.username || '',
      password: config.password || '',
      database: config.database || '',
      filePath: config.filePath || '',
      charset: config.charset || 'utf8mb4',
      timezone: config.timezone || '',
      sslMode: config.sslMode || 'disable',
      options: config.options || '',
      isDefault: config.isDefault || false
    }
    
    // 如果有高级选项则显示高级选项面板
    if (config.charset || config.timezone || config.sslMode || config.options || config.isDefault) {
      showAdvanced.value = true
    }
  } catch (error) {
    console.error('Failed to load connection config:', error)
    ElMessage.error('加载连接配置失败: ' + error.message)
  }
}

const getTypeLabel = (type) => {
  const labels = {
    [DatabaseTypes.MYSQL]: 'MySQL',
    [DatabaseTypes.POSTGRESQL]: 'PostgreSQL',
    [DatabaseTypes.SQLITE]: 'SQLite',
    [DatabaseTypes.SQLSERVER]: 'SQL Server',
    [DatabaseTypes.DAMENG]: 'Dameng'
  }
  return labels[type] || type
}

const getTypeIcon = (type) => {
  const icons = {
    [DatabaseTypes.MYSQL]: 'Coin',
    [DatabaseTypes.POSTGRESQL]: 'Coin',
    [DatabaseTypes.SQLITE]: 'Document',
    [DatabaseTypes.SQLSERVER]: 'Coin',
    [DatabaseTypes.DAMENG]: 'Coin'
  }
  return icons[type] || 'Coin'
}

const handleTypeChange = (type) => {
  // 编辑模式下不允许修改数据库类型
  // 这个方法保留是为了保持组件一致性
}

const selectSQLiteFile = async () => {
  try {
    // 这里应该调用Wails的文件选择API
    // 暂时使用模拟的文件路径
    const filePath = await showOpenFileDialog({
      filters: [
        { name: 'SQLite Database', extensions: ['db', 'sqlite', 'sqlite3'] },
        { name: 'All Files', extensions: ['*'] }
      ]
    })
    
    if (filePath) {
      form.value.filePath = filePath
    }
  } catch (error) {
    console.error('Failed to select file:', error)
    ElMessage.error('文件选择失败')
  }
}

// 模拟文件选择对话框（实际应用中应该使用Wails API）
const showOpenFileDialog = async (options) => {
  return new Promise((resolve) => {
    // 创建文件输入元素
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.db,.sqlite,.sqlite3'
    
    input.onchange = (e) => {
      const file = e.target.files[0]
      if (file) {
        resolve(file.name) // 实际应用中应该返回完整路径
      } else {
        resolve(null)
      }
    }
    
    input.click()
  })
}

const testConnection = async () => {
  try {
    await formRef.value.validate()
    
    testing.value = true
    
    // 验证配置
    const errors = validateConnectionConfig(form.value)
    if (errors.length > 0) {
      ElMessage.error(errors[0])
      return
    }
    
    // 测试连接
    await connectionStore.testConnection(form.value)
    ElMessage.success('连接测试成功')
    
  } catch (error) {
    ElMessage.error('连接测试失败: ' + error.message)
  } finally {
    testing.value = false
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // 验证配置
    const errors = validateConnectionConfig(form.value)
    if (errors.length > 0) {
      ElMessage.error(errors[0])
      return
    }
    
    // 更新连接配置
    const config = { ...form.value }
    await connectionStore.updateConnection(config)
    
    ElMessage.success('连接更新成功')
    emit('success', config)
    handleClose()
    
  } catch (error) {
    ElMessage.error('更新连接失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  form.value = {
    id: '',
    name: '',
    type: '',
    host: 'localhost',
    port: 3306,
    username: '',
    password: '',
    database: '',
    filePath: '',
    charset: 'utf8mb4',
    timezone: '',
    sslMode: 'disable',
    options: '',
    isDefault: false
  }
  
  showAdvanced.value = false
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}
</script>

<style scoped>
.connection-dialog :deep(.el-dialog__body) {
  padding: 16px;
}

.connection-form :deep(.el-form-item__label) {
  font-size: 13px;
}

.connection-form :deep(.el-form-item__content) {
  line-height: 32px;
}

.connection-form :deep(.el-card__header) {
  padding: 8px 12px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f9fafb;
}

.connection-form :deep(.el-card__body) {
  padding: 12px;
}

:deep(.el-dialog__header) {
  padding: 16px;
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-dialog__footer) {
  padding: 12px 16px;
  border-top: 1px solid #e4e7ed;
}

:deep(.el-dialog__headerbtn) {
  top: 16px;
}

/* 调整表单元素高度 */
:deep(.el-input__inner),
:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  height: 32px;
  line-height: 32px;
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  width: 24px;
}

:deep(.el-checkbox__label) {
  font-size: 13px;
}

/* 设置过渡效果 */
.transition-all {
  transition: all 0.3s ease;
}
</style> 